jQuery(function($) {

	/**
	 * Global variables
	 */
	var mapLayer = 'http://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png',
		mapOptions = {
			attribution: 'batdongsan',
			maxZoom: 20,
			id: 'vuquocvietkg.ikd1i1pc'
		},
		marker = {};

	/**
	 * Convert address string to latitude & longitude array, using Google map API
	 */
	$.addressLookup = function(address, callback) {
		var lookupUrl = 'https://maps.googleapis.com/maps/api/geocode/json?';
		$.getJSON(lookupUrl, {address: address}, function(data) {
			if (data.status == 'OK') {
				var pinPoint = data.results[0].geometry.location;
				callback([pinPoint.lat, pinPoint.lng]);
			}
		});
	}

	/**
	 * Look for hotel address & pin it to map
	 */
	$.fn.pinToMap = function() {
		return this.each(function() {
			var	$this = $(this),
				addition = $('.location_suggest_txt').val() || '',
				hotelId = $this.attr('id'),
				hotelName = $this.find('.hotel_name').text();
				address = $this.find('.hotel_contact_location').text() + ', ' + addition;
			if (address != '') {
				$.addressLookup(address, function(pinPoint) {
					marker['mark' + hotelId] = L.marker(pinPoint).addTo(map).bindPopup('<div class="hotel_map_popup">'+$this.html()+'</div>');
				});
			}
		});
	};

	/**
	 * Drop menu control
	 */
	$('.drop_list').on('mouseover mouseout', function(e) {
		$(this).find('.drop_menu').toggleClass('active', (e.type == 'mouseover'));
	});


	/**
	 * Booking form functioning
	 */

	var places = [
		{
			label: 'Singapore, Singapore',
			city: '132',
			country: 'SGP'
		},
		{
			label: 'Hochiminh, Vietnam',
			city: '185',
			country: 'VTN'
		},
	];
/*
	$('.location_suggest_txt').autocomplete({
		source: places,
		select: function(e, ui) {
			$('input[name="location[city]"]').val(ui.item.city);
			$('input[name="location[country]"]').val(ui.item.country);
			$('input[name="location[name]"]').val(ui.item.label);
			$(this).closest('form').find('.head_book_from').focus();
		}
	});

	$(".head_book_from").datepicker({
		minDate: 0,
		defaultDate: "1",
		onClose: function(selectedDate) {
			$(".head_book_to").datepicker("option", "minDate", selectedDate).focus();
		}
	});

	$(".head_book_to").datepicker({
		minDate: 0,
		defaultDate: "3",
		onClose: function( selectedDate ) {
			console.log('dah dah');
			$(".head_book_from").datepicker("option", "maxDate", selectedDate);
			$(this).closest('.booking_input').find('.drop_menu').addClass('active').find('input:eq(0)').focus();
		}
	});
*/
	$('.spinner').each(function() {
		$(this).spinner($(this).data());
	});

	/**
	 * Map view on hotel search result page
	 */

	$('#mapbox').each(function() {
		var $this = $(this);
		if ((baseLocation = $('.location_suggest_txt').val()) != '') {
			$.addressLookup(baseLocation, function(centerPoint) {
				map = L.map($this[0].id).setView(centerPoint, 13);
				L.tileLayer(mapLayer, mapOptions).addTo(map);
				$('.hotel_list li').pinToMap();
			});
		}
	});

	/**
	 * Filter hotel result by prices, using range slider
	 */

	$('#hotel_list').each(function() {
		var hotelList = $(this),
			priceMin = parseInt(hotelList.find('li:first .price_value').text()),
			priceMax = parseInt(hotelList.find('li:last .price_value').text()),
			priceAvg = (priceMax + priceMin) / 2;
			priceRangeMark = $('.filter_price_mark');
		priceRangeMark.find('li').text(priceAvg + ' pts');
		priceRangeMark.find('li:first').text(priceMin + ' pts');
		priceRangeMark.find('li:last').text(priceMax + ' pts');

		$('#filter_price_slider').slider({
			range: true,
			min: priceMin,
			max: priceMax,
			values: [priceMin, priceMax],
			slide: function(event, ui) {
				var valueMin = ui.values[0],
					valueMax = ui.values[1];
				hotelList.find('li').each(function() {
					var $this = $(this),
						hotelId = $this.attr('id'),
						price = parseInt($this.find('.price_value').text());
					$this.toggle((price >= valueMin) && (price <= valueMax));
					if ((price >= valueMin) && (price <= valueMax)) {

					}
					else {
						/*console.log(hotelId);
						console.log(marker);
						console.log(marker['mark' + hotelId]);*/
						// console.log(marker.235647);
						// map.removeLayer(marker.hotelId);
					}
				});
			}
		});
	});

	/**
	 * Mapbox on hotel profile page
	 */

	$('#hotel_address').each(function() {
		var address, addition;
		if ((address = $(this).text()) != '') {
			address = ((addition = $('.location_suggest_txt').val()) != '') ? address + ', ' + addition : address;
			console.log(address);
			$.addressLookup(address, function(pinPoint) {
				var map = L.map('hotel_mapbox').setView(pinPoint, 15),
					marker = L.marker(pinPoint).addTo(map);
				L.tileLayer(mapLayer, mapOptions).addTo(map);
			});
		}
	});

	/**
	 * Booking Terms & Conditions Dialog
	 */
	var bookingTncBtn = $('#booking_tnc_btn').on('click', function() {
		$('#booking_ntc').dialog({
			width: 560,
			height: 400,
			modal: true,
			buttons: {
				Agree: function() {
					$(this).dialog('close');
					$('#booking_agreement_checkbox').prop('checked', true);
				}
			}
		});
	});

	/**
	 * Booking form submittion
	 */
	$('#booking_form').on('submit', function(e) {
		if (!$('#booking_agreement_checkbox').is(':checked')) {
			console.log('blah');
			e.preventDefault();
			bookingTncBtn.click();
		}
	});

});